import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../common/index.dart';
import 'index.dart';

class MinePage extends GetView<MineController> {
  const MinePage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MineController>(
      init: MineController(),
      id: "mine",
      builder: (_) {
        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetsImages.mineBg),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(top: false, bottom: false, child: _buildView()),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return GetBuilder<MineController>(
      id: "main_view",
      builder: (_) {
        // 等待初始化完成
        if (!controller.is_initialized.value) {
          return Center(child: CircularProgressIndicator());
        }

        return Column(
          children: [
            SizedBox(height: 65.h),
            // 顶部导航按钮
            Row(
              children: [
                SizedBox(width: 24.w),
                GestureDetector(
                  onTap: () => controller.goto_chat_list(),
                  child: SvgPicture.asset(
                    AssetsImages.chat,
                    width: 40.w,
                    height: 40.h,
                  ),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () => controller.goto_setting(),
                  child: SvgPicture.asset(
                    AssetsImages.setting,
                    width: 40.w,
                    height: 40.h,
                  ),
                ),
                SizedBox(width: 24.w),
              ],
            ),
            SizedBox(height: 55.h),

            // 用户信息区域
            _buildUserInfoSection(),
            SizedBox(height: 20.h),

            // 订阅按钮
            _buildSubscriptionButton(),
            SizedBox(height: 16.h),

            // TabBar和TabBarView合并在一个Container中
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(40.r),
                    topRight: Radius.circular(40.r),
                  ),
                ),
                child: Column(
                  children: [
                    SizedBox(height: 16.h),
                    // TabBar 导航
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 24.w),
                      height: 40.h,
                      child: TabBar(
                        controller: controller.tab_controller,
                        indicator: BoxDecoration(color: Colors.transparent),
                        labelColor: Colors.white,
                        unselectedLabelColor: Colors.white70,
                        labelStyle: TextStyle(
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w900,
                          color: Colors.white,
                        ),
                        tabs: const [
                          Tab(text: 'My Posts'),
                          Tab(text: 'My Likes'),
                        ],
                      ),
                    ),
                    SizedBox(height: 18.h),

                    // TabBar 导航内容
                    Expanded(
                      child: TabBarView(
                        controller: controller.tab_controller,
                        children: [_build_posts_grid(), _build_likes_grid()],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  // 用户信息部分
  Widget _buildUserInfoSection() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Row(
        children: [
          SizedBox(width: 28.w),
          Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 4.w),
            ),
            child: Obx(
              () => CircleAvatar(
                backgroundImage:
                    controller.current_user.value?.avatar_image != null
                    ? ImagePath().get_avatar_image(
                        controller.current_user.value!.avatar_image!,
                      )
                    : ImagePath().get_avatar_image(AssetsImages.avatar),
                radius: 48.r,
              ),
            ),
          ),
          SizedBox(width: 16.w),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Obx(() {
                // 限制用户名最多显示12个字符
                String displayName =
                    controller.current_user.value?.name?.toUpperCase() ??
                    'USERNAME';
                if (displayName.length > 12) {
                  displayName = displayName.substring(0, 12);
                }

                return Row(
                  children: [
                    // 用户名和VIP标志在同一行
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          displayName,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        // VIP标志紧跟用户名后面
                        if (controller.current_user.value?.is_vip == true)
                          Container(
                            margin: EdgeInsets.only(left: 6.w),
                            padding: EdgeInsets.symmetric(
                              horizontal: 6.w,
                              vertical: 3.h,
                            ),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [Color(0xFF1E2E3D), Color(0xFF273747)],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(8.r),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.3),
                                  blurRadius: 3,
                                  offset: Offset(0, 1),
                                ),
                              ],
                              border: Border.all(
                                color: Color(0xFF4CAF50),
                                width: 1.w,
                              ),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  Icons.verified_user,
                                  color: Color(0xFF4CAF50),
                                  size: 8.sp,
                                ),
                                SizedBox(width: 3.w),
                                Text(
                                  'VIP',
                                  style: TextStyle(
                                    color: Color(0xFF4CAF50),
                                    fontSize: 9.sp,
                                    fontWeight: FontWeight.w900,
                                    letterSpacing: 0.5,
                                  ),
                                ),
                              ],
                            ),
                          ),
                      ],
                    ),
                  ],
                );
              }),
              GestureDetector(
                onTap: () => _show_edit_signature_dialog(),
                child: Container(
                  width: 180.w,
                  padding: EdgeInsets.symmetric(vertical: 4.h),
                  child: Row(
                    children: [
                      SvgPicture.asset(
                        AssetsImages.edit,
                        width: 10.w,
                        height: 10.h,
                      ),
                      SizedBox(width: 4.w),
                      Expanded(
                        child: Obx(
                          () => Text(
                            controller.current_user.value?.signature
                                    ?.toUpperCase() ??
                                "NOTHING LEFT",
                            style: TextStyle(
                              color: Colors.white70,
                              fontSize: 12.sp,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          Spacer(),
          SizedBox(width: 16.w),
        ],
      ),
    );
  }

  // 显示编辑签名对话框
  void _show_edit_signature_dialog() {
    final currentSignature = controller.current_user.value?.signature ?? '';
    final textController = TextEditingController(text: currentSignature);
    final signatureLengthNotifier = ValueNotifier<int>(currentSignature.length);
    final isEmptyNotifier = ValueNotifier<bool>(currentSignature.isEmpty);
    final maxLength = 50;

    // 获取初始焦点
    final FocusNode focusNode = FocusNode();

    // 延迟获取焦点
    Future.delayed(Duration(milliseconds: 100), () {
      focusNode.requestFocus();
    });

    SmartDialog.show(
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: GestureDetector(
          // 点击空白处关闭键盘
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child: SingleChildScrollView(
            // 使用SingleChildScrollView避免溢出
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.9),
                borderRadius: BorderRadius.circular(20.r),
                border: Border.all(
                  color: Colors.white.withOpacity(0.2),
                  width: 1.w,
                ),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min, // 确保列只占用需要的空间
                children: [
                  // 标题栏
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(20.r),
                        topRight: Radius.circular(20.r),
                      ),
                      color: Colors.black.withOpacity(0.7),
                    ),
                    child: Center(
                      child: Text(
                        'Edit Signature',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),

                  // 分隔线
                  Divider(height: 1.h, color: Colors.white.withOpacity(0.1)),

                  // 内容区域
                  Padding(
                    padding: EdgeInsets.all(20.w),
                    child: Column(
                      mainAxisSize: MainAxisSize.min, // 确保列只占用需要的空间
                      children: [
                        // 输入框
                        TextField(
                          controller: textController,
                          focusNode: focusNode,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                          ),
                          maxLength: maxLength,
                          maxLines: 2,
                          minLines: 1,
                          buildCounter:
                              (
                                _, {
                                required currentLength,
                                required isFocused,
                                maxLength,
                              }) => null,
                          decoration: InputDecoration(
                            hintText: 'What describes you best?',
                            hintStyle: TextStyle(color: Colors.grey[400]),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: Colors.white.withOpacity(0.3),
                              ),
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.green),
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 12.h,
                            ),
                            filled: true,
                            fillColor: Colors.black.withOpacity(0.5),
                          ),
                          onChanged: (value) {
                            signatureLengthNotifier.value = value.length;
                            isEmptyNotifier.value = value.trim().isEmpty;
                          },
                        ),

                        SizedBox(height: 10.h),

                        // 计数器
                        Align(
                          alignment: Alignment.centerRight,
                          child: ValueListenableBuilder<int>(
                            valueListenable: signatureLengthNotifier,
                            builder: (context, length, child) {
                              final color = length > maxLength * 0.8
                                  ? (length > maxLength
                                        ? Colors.red
                                        : Colors.orange)
                                  : Colors.grey;
                              return Text(
                                '$length/$maxLength',
                                style: TextStyle(color: color, fontSize: 12.sp),
                              );
                            },
                          ),
                        ),

                        SizedBox(height: 20.h),

                        // 使用GetBuilder替代Obx来避免嵌套响应式问题
                        GetBuilder<MineController>(
                          id: "signature_dialog",
                          builder: (_) {
                            return Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                // 取消按钮
                                Expanded(
                                  child: ElevatedButton(
                                    onPressed:
                                        controller.is_updating_signature.value
                                        ? null
                                        : () => SmartDialog.dismiss(),
                                    style: ElevatedButton.styleFrom(
                                      backgroundColor: Colors.grey.withOpacity(
                                        0.3,
                                      ),
                                      foregroundColor: Colors.white,
                                      disabledBackgroundColor: Colors.grey
                                          .withOpacity(0.1),
                                      disabledForegroundColor: Colors.white
                                          .withOpacity(0.3),
                                      elevation: 0,
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(
                                          25.r,
                                        ),
                                      ),
                                      padding: EdgeInsets.symmetric(
                                        vertical: 12.h,
                                      ),
                                    ),
                                    child: Text(
                                      'Cancel',
                                      style: TextStyle(fontSize: 16.sp),
                                    ),
                                  ),
                                ),

                                SizedBox(width: 16.w),

                                // 保存按钮
                                Expanded(
                                  child: ValueListenableBuilder<bool>(
                                    valueListenable: isEmptyNotifier,
                                    builder: (context, isEmpty, child) {
                                      return ElevatedButton(
                                        onPressed:
                                            controller
                                                    .is_updating_signature
                                                    .value ||
                                                isEmpty
                                            ? null
                                            : () {
                                                final newSignature =
                                                    textController.text.trim();
                                                controller.edit_signature(
                                                  newSignature,
                                                );
                                              },
                                        style: ElevatedButton.styleFrom(
                                          backgroundColor: Colors.green,
                                          foregroundColor: Colors.white,
                                          disabledBackgroundColor: Colors.green
                                              .withOpacity(0.3),
                                          disabledForegroundColor: Colors.white
                                              .withOpacity(0.5),
                                          elevation: 0,
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(
                                              25.r,
                                            ),
                                          ),
                                          padding: EdgeInsets.symmetric(
                                            vertical: 12.h,
                                          ),
                                        ),
                                        child:
                                            controller
                                                .is_updating_signature
                                                .value
                                            ? SizedBox(
                                                width: 20.w,
                                                height: 20.h,
                                                child:
                                                    CircularProgressIndicator(
                                                      color: Colors.white,
                                                      strokeWidth: 2.w,
                                                    ),
                                              )
                                            : Text(
                                                'Save',
                                                style: TextStyle(
                                                  fontSize: 16.sp,
                                                ),
                                              ),
                                      );
                                    },
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      maskColor: Colors.black.withOpacity(0.7),
      onMask: () => SmartDialog.dismiss(),
      alignment: Alignment.bottomCenter,
    );
  }

  // 订阅按钮
  Widget _buildSubscriptionButton() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: GestureDetector(
        onTap: () => controller.goto_subscription(),
        child: Container(
          width: 343.w,
          height: 50.h,
          decoration: ShapeDecoration(
            color: Colors.black.withValues(alpha: 0.40),
            shape: RoundedRectangleBorder(
              side: BorderSide(width: 1, color: Colors.white),
              borderRadius: BorderRadius.circular(16),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.card_membership, color: Colors.white, size: 20.sp),
              SizedBox(width: 8.w),
              Text(
                'Subscription',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w900,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 帖子网格
  Widget _build_posts_grid() {
    if (controller.is_loading.value) {
      return Center(child: CircularProgressIndicator());
    }

    if (controller.my_posts.isEmpty) {
      return Center(
        child: Text('No posts yet', style: TextStyle(color: Colors.white70)),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        padding: EdgeInsets.only(top: 0), // No top padding
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 8.w,
          mainAxisSpacing: 8.h,
          childAspectRatio: 0.75,
        ),
        itemCount: controller.my_posts.length, // 限制项目数量，避免索引越界
        itemBuilder: (context, index) {
          // 添加安全检查，确保索引有效
          if (index >= controller.my_posts.length) {
            return Container(); // 返回空容器
          }

          final post = controller.my_posts[index];
          final user = controller.current_user.value;

          // 使用帖子图片，如果不存在则使用备用图像
          return _buildGridItem(user: user, post: post, isFavorited: false);
        },
      ),
    );
  }

  // 喜欢网格
  Widget _build_likes_grid() {
    if (controller.is_loading.value) {
      return Center(child: CircularProgressIndicator());
    }

    if (controller.my_likes.isEmpty) {
      return Center(
        child: Text('No likes yet', style: TextStyle(color: Colors.white70)),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        padding: EdgeInsets.only(top: 0), // No top padding
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 8.w,
          mainAxisSpacing: 8.h,
          childAspectRatio: 0.75,
        ),
        itemCount: controller.my_likes.length, // 限制项目数量，避免索引越界
        itemBuilder: (context, index) {
          // 添加安全检查，确保索引有效
          if (index >= controller.my_likes.length) {
            return Container(); // 返回空容器
          }

          final post = controller.my_likes[index];
          final user = controller.current_user.value;

          // 使用帖子图片，如果不存在则使用备用图像
          return _buildGridItem(user: user, post: post, isFavorited: true);
        },
      ),
    );
  }

  // 网格项
  Widget _buildGridItem({
    required UserModel? user,
    required PostModel post,
    required bool isFavorited,
  }) {
    // 获取帖子发布者信息
    final postCreator = UserService().get_user_data_by_id(post.user_id ?? '');

    // 尝试使用帖子图片，如果失败则使用备用图片
    ImageProvider imageProvider;
    try {
      if (post.post_image_list is List &&
          (post.post_image_list as List).isNotEmpty) {
        // 如果imageList是列表且不为空，使用第一张图片
        final firstImage = (post.post_image_list as List)[0]?.toString() ?? '';
        imageProvider = firstImage.isNotEmpty
            ? ImagePath().get_post_image(firstImage)
            : AssetImage(AssetsImages.defaultPost) as ImageProvider;
      } else if (post.post_image_list is String &&
          (post.post_image_list as String).isNotEmpty) {
        // 如果imageList是字符串，可能是逗号分隔的路径，分割并使用第一个
        final imagePaths = (post.post_image_list as String).split(',');
        if (imagePaths.isNotEmpty && imagePaths[0].trim().isNotEmpty) {
          final firstImagePath = imagePaths[0].trim();
          imageProvider = ImagePath().get_post_image(firstImagePath);
        } else {
          imageProvider = AssetImage(AssetsImages.defaultPost);
        }
      } else {
        // 其他情况，使用备用图片
        imageProvider = AssetImage(AssetsImages.defaultPost);
      }
    } catch (e) {
      // 如果帖子图片加载失败，使用备用图片
      debugPrint('帖子图片加载失败: ${post.post_image_list}, 使用备用图片: $e');
      imageProvider = AssetImage(AssetsImages.defaultPost);
    }

    return GestureDetector(
      onTap: () => controller.goto_post_detail(post),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          image: DecorationImage(image: imageProvider, fit: BoxFit.cover),
        ),
        child: Stack(
          children: [
            // 底部渐变，提高文字可见度
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 50.h,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Colors.transparent, Colors.black.withOpacity(0.7)],
                  ),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(12.r),
                    bottomRight: Radius.circular(12.r),
                  ),
                ),
              ),
            ),
            // 用户信息
            Positioned(
              bottom: 8.h,
              left: 8.w,
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 12.r,
                    backgroundImage:
                        postCreator?.avatar_image != null &&
                            postCreator!.avatar_image!.isNotEmpty
                        ? ImagePath().get_avatar_image(
                            postCreator.avatar_image!,
                          )
                        : ImagePath().get_avatar_image(AssetsImages.avatar),
                  ),
                  SizedBox(width: 4.w),
                  Text(
                    postCreator?.name?.isNotEmpty == true
                        ? postCreator!.name!.toLowerCase()
                        : 'unknown',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
            // 收藏图标
            Positioned(
              bottom: 8.h,
              right: 8.w,
              child: Icon(
                isFavorited ? Icons.favorite : Icons.favorite_border,
                color: isFavorited ? Colors.red : Colors.white,
                size: 20.sp,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
